<?php

namespace App\Jobs\Zhunya;

use App\Models\CacheModel\zl3\Zl3FortuneYearAnalysis;
use App\Models\CacheModel\zl3\Zl3FortuneYearAnalysisIsNew;
use App\Tools\HoroscopeFortune;
use Log;
use AstroTools\cache\CacheManage;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class FortuneYearAnalysisJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function task()
    {
      $jobData = $this->jobData;
      // $jobData = [
        //     'id' => 1  // 计算数据 ID     zl3_fortune_year_analysis表ID
        // ];
        // $jobAttempts = $job->attempts();
        // if ($jobAttempts > 2)
        // {   // 失败两次 则删除
        //     $job->delete();
        //     return;
        // }

        $nowTime = time();
        $FortuneYearAnalysisModel = new Zl3FortuneYearAnalysis();
        $info = $FortuneYearAnalysisModel->where('id', $jobData['id'])->find();
        try
        {
            // 档案信息
            $recodeInfo = json_decode($info['recode_info'], true);
            $resData = [];
            // 接入计算逻辑
            switch ($info['type'])
            {
                case 1:
                    $resData = HoroscopeFortune::getInstance()->setRecord($recodeInfo)->setAdvance(date('Y'))->nianyunQifu();
                    break;
                case 2:
                    $year = substr((string)$info['stageyear'], 0, 4);
                    $resData = HoroscopeFortune::getInstance()->setRecord($recodeInfo)->setAdvance($year . '-06-30')->renshengjieduan();
                    break;
                case 3:
                    $resData = HoroscopeFortune::getInstance()->setRecord($recodeInfo)->setAdvance(date('Y-06-30'))->liunianShaixuan();
                    break;
            }

            $updateData = [
                'content' => json_encode($resData, JSON_UNESCAPED_UNICODE),
                'status' => 2,
                'start_time' => $nowTime,
                'end_time' => time()
            ];
            if ((int)$info['type'] === 1)
            {// 一生起伏    更新档案 hashkey
                $recodeHashKey = Util::getRecodeHashKey($recodeInfo);
                if ($recodeHashKey !== $info['hash'])
                {
                    $updateData['hash'] = $recodeHashKey;
                }
            }
            $FortuneYearAnalysisModel->where('id', $jobData['id'])->update($updateData);

            if ($info['order_num'])
            {
                (new Zl3FortuneYearAnalysisIsNew())->setNewStatus($info['uid'], $info['rid'], $info['type'], (int)$info['stageyear'], 1);
                (new \app\common\cachemodel\Orders())->UpdateData($info['order_num'], ['status' => 4], 4);
            }
        }
        catch (\Exception $e)
        {
            Log::write('年运分析 报告【一生起伏｜人生阶段｜年运筛查】计算异常 jobData：' . json_encode($jobData, JSON_UNESCAPED_UNICODE) . ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine(), 'error');
            // 计算失败
            $extend = [
                'msg' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ];
            $FortuneYearAnalysisModel->where('id', $jobData['id'])->update(['status' => 3, 'start_time' => $nowTime, 'end_time' => time(), 'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)]);
        }

        // 删除缓存
        $key = $info['uid'] . ':' . $info['rid'];
        CacheManage::getInstance()->setCacheConfig('fortune.fortune_year_analysis', $key)->rmCache();

        $job->delete();
    }
}